package com.hoopchina.ui.details;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.hoopchina.ui.details.MD5;

import android.net.Uri;
/**
 * 获取网络图片业务bean,具有缓存功能
 */
public class ImageService {
	/**
	 * 获取文件后缀
	 */
	private static String getExt(String path) {
		return path.substring(path.lastIndexOf('.'));
	}
	/**
	 * 缓存图片
	 * @param path 图片路径
	 * @param saveDir 缓存目录
	 * @return 图片在缓存目录的路径
	 * @throws Exception
	 */
	public static Uri cacheImage(String path, File saveDir) throws Exception {
		File file = new File(saveDir, MD5.getMD5(path) + getExt(path));
		if (file.exists()) {// 判断是否存在缓存图片
			return Uri.fromFile(file);
		} else {
			FileOutputStream outStream = new FileOutputStream(file);
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5 * 1000);
			conn.setRequestMethod("GET");
			if (conn.getResponseCode() == 200) {
				InputStream inStream = conn.getInputStream();
				copyStream(inStream, outStream);
				return Uri.fromFile(file);
			} else {
				throw new Exception("request image fail");
			}
		}
	}
	
	private static void copyStream(InputStream inStream, OutputStream outStream)
			throws Exception {
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		outStream.close();
		inStream.close();
	}
}
